package com.hnkywl.sts.action.sys;

import com.hnkywl.sts.dao.sys.PmDao;
import com.hnkywl.sts.dao.sys.ZdjDao;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sys.Pm;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.entity.sys.Zdj;
import com.hnkywl.sts.entity.zjgl.Pj;
import com.hnkywl.sts.service.sys.YgService;
import com.hnkywl.sts.service.sys.ZdjService;
import com.hnkywl.sts.util.POIUtil;
import jxl.Sheet;
import jxl.Workbook;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.Region;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.hibernate.tool.hbm2x.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * 说明：
 * 包:        com.hnkywl.sts.action.sfgl
 * 类描述:    岗位Action类
 * 修改备注: [说明本次修改内容]
 * 版本:        [v1.0]
 */
@Namespace("/sys/zdj")
public class ZdjAction extends SimpleActionSupport {
    private ZdjService zdjService;
    private int page;
    //分页组件 页面大小
    private int rows = 10;
    private String sysDate;
    private PmDao pmDao;
    private File upload;
    private ZdjDao zdjDao;
    private Date zdjStartDate;
    private Date zdjEndDate;
    private String pmName;
    private Long id;
    private Double zdj;

    @Action("zdj")
    public String zdj() {
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        sysDate = simple.format(new Date());
        return SUCCESS;
    }

    //员工的查询分页显示
    @Action("zdjList")
    public void ygList() {
        if (zdjStartDate != null)
            zdjStartDate = convertDate(zdjStartDate, true);
        if (zdjEndDate != null)
            zdjEndDate = convertDate(zdjEndDate, false);
        this.renderJson(this.zdjService.findAllZdjList(pmName, zdjStartDate, zdjEndDate, page, rows));
    }

    @Action("save_zdj")
    public void saveZdj() {
        try {
            this.zdjService.saveZdj(id, zdj);
            renderJson("{\"statusCode\":200,\"id\":" + id + "}");
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":300,\"message\":\"" + e.getMessage() + "\"}");
        }

    }

    //指导价
    @Action("zdj_export")
    public String skshShPjExport() {
//        List<Map> pmList = new ArrayList<Map>();
        List<Map> pmList = pmDao.findAllPm(YgService.getCurrentYg().getZggs().getId());
        //第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        POIUtil poiUtil = new POIUtil(wb);
        //设置列宽
        sheet.setDefaultRowHeightInPoints(15);
        sheet.setDefaultColumnWidth((short) 12);
        sheet.setColumnWidth((short) 0, (short) (20 * 512));
        sheet.setColumnWidth((short) 1, (short) (20 * 512));
        sheet.setColumnWidth((short) 2, (short) (20 * 512));
        //第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        row.setHeightInPoints(36);
        //第四步，创建单元格，并设置值表头  设置表头居中
        HSSFCellStyle titleStyle = poiUtil.createTitleHSSFCellStyle(wb);
        HSSFCell titleCell = row.createCell((short) 0);
        titleCell.setCellStyle(titleStyle);
        titleCell.setEncoding(HSSFCell.ENCODING_UTF_16);
        titleCell.setCellValue("指导价导入文件");
        sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) 2));
        //生成第一行数据...表头
        HSSFCellStyle headerStyle = poiUtil.createHeader3HSSFCellStyle(wb);
        poiUtil.fillRow(sheet, headerStyle, 1, "编码", "品名", "指导价格");
        //生成从第二行开始的品名数据
        for (int i = 2; i < pmList.size() + 2; i++) { //从第三行开始导入
            poiUtil.fillRow(sheet, headerStyle, i, pmList.get(i - 2).get("CODE"), pmList.get(i - 2).get("NAME"), "");
        }
        try {
            response.setContentType("application/x-download");
            String filedisplay = new String(("指导价批量入账表.xls").getBytes("gb2312"), "iso8859-1");
            response.addHeader("Content-Disposition", "attachment;filename=" + filedisplay);
            wb.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            renderText("位置异常，导出失败" + e.getMessage());
        }
        return null;
    }

    //指导价批量导入
    @Action("zdj_import")
    public void zdjImport() {
        try {
            List<Zdj> zdjList = zdjDao.findZdjByDrrq(new Date());
            if (zdjList != null && zdjList.size() > 0) {
                for (Zdj z1 : zdjList) {
                    zdjService.deleteZdj(z1);
                }
            }
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd");
            Workbook book = Workbook.getWorkbook(upload);
            //  获得第一个工作表对象
            Sheet sheet = book.getSheet(0);
            //获取总行数
            int rows = sheet.getRows();
            List<Pj> pjList = new ArrayList<Pj>();
            for (int i = 2; i < rows; i++) { //从第三行开始导入
                Zdj z = new Zdj();
                if (sheet.getCell(0, i) != null && StringUtils.isNotEmpty(sheet.getCell(0, i).getContents())) {//第一列 编码
                    Pm p = pmDao.findByCode(sheet.getCell(0, i).getContents());
                    z.setPm(p);
                } else {
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行编码为空\"}");
                    return;
                }
                Double jg;
                Pattern pattern = Pattern.compile("[0-9]*");
                if(sheet.getCell(2, i)==null || StringUtils.isEmpty(sheet.getCell(2, i).getContents())){
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行指导价为空\"}");
                    return;
                }else if(!pattern.matcher(sheet.getCell(2, i).getContents()).matches()){
                    renderText("{\"statusCode\":\"300\", \"message\":\"第" + (i + 1) + "行指导价不为数字\"}");
                    return;
                } else {
                    jg = Double.parseDouble(sheet.getCell(2, i).getContents().toString());
                    z.setZdj(jg);
                }
                z.setDrrq(new Date());
                z.setMj(YgService.getCurrentYg().getZggs());
                z.setCreateUser(YgService.getCurrentYg());
                z.setCreateOrgan(YgService.getCurrentYg().getZggs());
                z.setCreateDepartment(YgService.getCurrentYg().getZgjg());
                z.setDateCreated(new Date());
                z.setLastUpdated(z.getDateCreated());
                zdjService.saveZdj(z);
            }
            //计算所有未入库卡号的控货单价
//            zdjService.jsWrkKhKhdj();
            renderText("{\"statusCode\":\"200\", \"message\":\"指导价批量导入成功！\"}");
        } catch (Exception e) {
            e.printStackTrace();
            renderText("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }


    /**
     * @param date
     * @param flag true:当天00:00:00   false:第二天00:00:00
     * @return
     */
    private Date convertDate(Date date, boolean flag) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        if (!flag)
            gc.add(GregorianCalendar.DAY_OF_MONTH, 1);
        gc.set(GregorianCalendar.HOUR, 0);
        gc.set(GregorianCalendar.MINUTE, 0);
        gc.set(GregorianCalendar.SECOND, 0);
        return gc.getTime();
    }


    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public String getSysDate() {
        return sysDate;
    }

    public void setSysDate(String sysDate) {
        this.sysDate = sysDate;
    }

    public File getUpload() {
        return upload;
    }

    public void setUpload(File upload) {
        this.upload = upload;
    }

    public Date getZdjStartDate() {
        return zdjStartDate;
    }

    public void setZdjStartDate(Date zdjStartDate) {
        this.zdjStartDate = zdjStartDate;
    }

    public Date getZdjEndDate() {
        return zdjEndDate;
    }

    public void setZdjEndDate(Date zdjEndDate) {
        this.zdjEndDate = zdjEndDate;
    }

    public String getPmName() {
        return pmName;
    }

    public void setPmName(String pmName) {
        this.pmName = pmName;
    }

    public ZdjService getZdjService() {
        return zdjService;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Double getZdj() {
        return zdj;
    }

    public void setZdj(Double zdj) {
        this.zdj = zdj;
    }

    @Autowired
    public void setZdjService(ZdjService zdjService) {
        this.zdjService = zdjService;
    }

    @Autowired
    public void setPmDao(PmDao pmDao) {
        this.pmDao = pmDao;
    }

    @Autowired
    public void setZdjDao(ZdjDao zdjDao) {
        this.zdjDao = zdjDao;
    }
}
